package net.lesscoding.future;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.ExecutionException;

/**
 * @author eleven
 * @date 2024/10/28 14:08
 * @apiNote
 */
@Slf4j
public class NettyPromiseTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1. 准备 eventLoop 对象
        NioEventLoopGroup group = new NioEventLoopGroup();
        EventLoop eventLoop = group.next();
        // 2. 主动创建 Promise 对象
        DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);

        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            int result = new Random().nextInt();
            log.info("随机生成结果: {}", result);
            if (result % 2 == 0) {
                promise.setSuccess(result);
            } else {
                promise.setFailure(new RuntimeException("计算失败"));
            }
        }).start();

        log.info("等待结果");
        log.info("结果是 {}", promise.get());

    }
}
